package com.lx.api.weight;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lx.api.utils.ListExcelExporter;
import com.lx.core.weight.entity.GoodsType;
import com.lx.core.weight.entity.WeightBridgeNumber;
import com.lx.core.weight.entity.dto.EmployerStaticDTO;
import com.lx.core.weight.entity.dto.WeightPageDTO;
import com.lx.core.weight.entity.vo.*;
import com.lx.core.weight.service.GoodsTypeService;
import com.lx.core.weight.service.WeightBridgeNumberService;
import com.lx.core.weight.service.WeightService;
import com.lx.framework.common.R;
import com.lx.framework.core.entity.SysAdmin;
import com.lx.framework.core.model.SysAdminDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lx
 * @date 2025/08/26 09:11
 **/
@RestController
@Api(tags = "称重管理")
@RequestMapping("/weight/weight")
public class WeightController {

    private final WeightService weightService;

    private final GoodsTypeService goodsTypeService;

    private final WeightBridgeNumberService weightBridgeNumberService;

    public WeightController(WeightService weightService, GoodsTypeService goodsTypeService, WeightBridgeNumberService weightBridgeNumberService) {
        this.weightService = weightService;
        this.goodsTypeService = goodsTypeService;
        this.weightBridgeNumberService = weightBridgeNumberService;
    }

    @ApiOperation(value = "获取称重列表分页")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = WeightVO.class))
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public R page(@RequestBody WeightPageDTO weightPageDTO) {

        IPage<WeightVO> page = new Page<>(weightPageDTO.getCurrent(), weightPageDTO.getSize());
        WeightVO weightVO = this.weightService.page(page, weightPageDTO);
        return R.success("操作成功", weightVO);
    }


    @ApiOperation(value = "导出")
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "返回 Excel 文件流"),
//            @ApiResponse(code = 500, message = "导出失败")
//    })
    @GetMapping(value = "/exportExcel", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    public void exportExcel(@ApiIgnore HttpServletResponse response, @ModelAttribute WeightPageDTO weightPageDTO) throws IOException {
        try {
            // 1. 设置响应头
            ListExcelExporter.setResponseHeaders(response, "称重列表.xlsx");

            // 2. 查询数据
            List<WeightPageList> weightPageLists = this.weightService.exportExcel(weightPageDTO);
            if (weightPageLists == null) {
                weightPageLists = new ArrayList<>();
            }
            // 3. 生成Excel并写入响应流
            ListExcelExporter.generateExcel(response, weightPageLists, weightPageDTO);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace(); // 记录日志
            try {
                ListExcelExporter.setResponseHeaders(response, "导出失败_" + System.currentTimeMillis() + ".xlsx");
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("错误");
                Row row = sheet.createRow(0);
                row.createCell(0).setCellValue("导出失败：" + e.getMessage());
                workbook.write(response.getOutputStream());
                workbook.close();
                response.flushBuffer();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    @ApiOperation(value = "获取所有货物名称")
    @RequestMapping(value = "/goodsType", method = RequestMethod.GET)
    public R getGoodsType() {
        List<GoodsType> goodsTypeNameList = this.goodsTypeService.getGoodsTypeNameList();
        return R.success("操作成功", goodsTypeNameList);
    }

    @ApiOperation(value = "获取所有称重编号")
    @RequestMapping(value = "/weightNumber", method = RequestMethod.GET)
    public R getWeightNumber() {
        List<WeightBridgeNumber> weightNumberList = this.weightBridgeNumberService.getWeightBridgeNumberList();
        return R.success("操作成功", weightNumberList);
    }

    @ApiOperation(value = "获取当天所需要的数据")
    @RequestMapping(value = "/getCurrentDayData", method = RequestMethod.GET)
    public R getCurrentDayData() {
        CurrentDayDataVO currentDayDataVO = this.weightService.getCurrentDayData();
        return R.success("操作成功", currentDayDataVO);
    }

    @ApiOperation(value = "获取当天所货物种类分布")
    @RequestMapping(value = "/getCurrentGoodsType", method = RequestMethod.GET)
    public R getCurrentGoodsType() {
        List<CurrentDayGoodsWeightVO> currentDayGoodsWeightVO = this.weightService.getCurrentDayGoodsWeight();
        return R.success("操作成功", currentDayGoodsWeightVO);

    }

    @ApiOperation(value = "获取最近七天货物平均价")
    @RequestMapping(value = "/getLastSevenDayAveragePrice", method = RequestMethod.GET)
    public R getLastSevenDayAveragePrice(@RequestParam(name = "goodsType", defaultValue = "-1") int goodsType) {
        List<PriceLastSevenGoodsVO> priceLastSevenGoodsVO = this.weightService.getLastSevenDayAveragePrice(goodsType);
        return R.success("操作成功", priceLastSevenGoodsVO);
    }

    @ApiOperation(value = "获取最近一个月费用展示信息")
    @RequestMapping(value = "/getLastMonthDayFee", method = RequestMethod.GET)
    public R getLastMonthDayFee(@RequestParam(name = "goodsType", defaultValue = "-1") int goodsType) {
        List<FeeLastMonthVO> feeLastMonthVO = this.weightService.getLastMonthDayFee(goodsType);
        return R.success("操作成功", feeLastMonthVO);
    }

    @ApiOperation(value = "获取当天地磅使用情况")
    @RequestMapping(value = "/getCurrentWeightNumberUse", method = RequestMethod.GET)
    public R getCurrentWeightNumberUse(@RequestParam(name = "goodsType", defaultValue = "-1") int goodsType) {
        List<WeightNumberUseInfoVO> weightNumberUseInfoVO = this.weightService.getCurrentWeightNumberUse(goodsType);
        return R.success("操作成功", weightNumberUseInfoVO);
    }

    @ApiOperation(value = "获取用户信息页面")
    @RequestMapping(value = "/getSyaAdminPage", method = RequestMethod.GET)
    public R getSyaAdminPage(Integer current, Integer size, String username) {
        IPage<SysAdminDTO> page = new Page<>(current, size);
        Page<SysAdminDTO>  returnPage = this.weightService.getSyaAdminPage(page,username);
        return R.success("操作成功", returnPage);
    }


    @ApiOperation(value = "统计过磅员过磅个数")
    @RequestMapping(value = "/getEmployerWeightCount", method = RequestMethod.POST)
    public R getEmployerWeightCount(@RequestBody EmployerStaticDTO employerStaticDTO)
    {
        IPage<EmployerWeightCountVO> page = new Page<>(employerStaticDTO.getCurrent(), employerStaticDTO.getSize());
        EmployerWeightCountVO employerWeightCountVO = this.weightService.getEmployerWeightCount(page, employerStaticDTO);
        return R.success("操作成功", employerWeightCountVO);
    }
}
